<template>


  <div class="medical-record-container">
    <!-- 左侧患者信息区域 -->
    <div class="left-section">
      <div class="form-item">
        <label>患者姓名</label>

        <el-form-item label="患者名称">
          <el-input placeholder="请输入患者姓名" v-model="patientNew.patientName" :readonly="patientNew">
            <template #suffix>
              <el-icon class="icon" size="18" @click="getpatient('1')">
                <User />
                <!-- 这里的 user 应该是你自定义的图标组件，确保已经正确注册 -->
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
      </div>
      <div class="form-item">
        <label>身份证号</label>
        <el-input placeholder="请输入身份证号" v-model="patientNew.idCard" readonly />
      </div>
      <div class="form-item">
        <label>患者电话</label>
        <el-input placeholder="请输入患者电话" v-model="patientNew.phone" readonly />
      </div>
      <div class="form-item">
        <label>性别</label>
        <el-radio-group v-model="patientNew.sex" :disabled="true">
          <el-radio value="0">男</el-radio>
          <el-radio value="1">女</el-radio>
          <el-radio value="2">未知</el-radio>
        </el-radio-group>
      </div>
      <div class="form-item">
        <label>出生日期</label>
        <el-date-picker type="date" placeholder="请选择出生日期" v-model="patientNew.birthday" readonly />
      </div>
      <div class="form-item">
        <label>患者年龄</label>
        <el-input placeholder="请输入患者年龄" readonly v-model="patientNewAge" />
      </div>
      <div class="form-item">
        <label>地址信息</label>
        <el-input placeholder="请输入地址信息" :maxlength="30" show-word-limit v-model="patientNew.address" readonly />
      </div>
      <div class="form-item">
        <label>过敏史</label>
        <el-input placeholder="请输入过敏史" :maxlength="100" show-word-limit v-model="patientNew.allergyInfo" readonly />
      </div>
      <div class="patient-archive">
        <el-tabs>
          <el-tab-pane label="患者档案">
            <div v-if="!activeTab">暂无患者档案</div>
            <span>
              <div class="patient-profile">
                <div v-if="activeTab">
                  <div class="profile-container">
                    <!-- 基本信息列 -->
                    <div class="column">
                      <div class="field">
                        <label>ID:</label>
                        <span :text="PatientFiles.patientId">aa{{ PatientFiles.patientId }}</span>
                      </div>
                      <div class="field">
                        <label>姓名:</label>
                        <span></span>
                      </div>
                      <div class="field">
                        <label>身份证号:</label>
                        <span>{{ PatientFiles.idCard }}</span>
                      </div>
                      <div class="field">
                        <label>电话:</label>
                        <span>{{ PatientFiles.phone }}</span>
                      </div>
                      <div class="field">
                        <label>性别:</label>
                        <span>{{ PatientFiles.sex != 0 ? '女' : '男' }}</span>
                      </div>
                      <div class="field">
                        <label>出生年月:</label>
                        <span>{{ PatientFiles.birthday }}</span>
                      </div>
                      <div class="field">
                        <label>地址信息:</label>
                        <span>{{ PatientFiles.address }}</span>
                      </div>
                    </div>
                  </div>
                  <!-- 医疗信息列 -->
                  <div class="column">
                    <div class="field">
                      <label>过敏信息:</label>
                      <span>{{ PatientFiles.allergyInfo || '无' }}</span>
                    </div>
                    <div class="field">
                      <label>血型:</label>
                      <span>{{ PatientFile.bloodType || '未填写' }}</span>
                    </div>
                    <div class="field">
                      <label>身高:</label>
                      <span>{{ PatientFile.height || '未测量' }}</span>
                    </div>
                    <div class="field">
                      <label>体重:</label>
                      <span>{{ PatientFile.weight || '未测量' }}</span>
                    </div>
                    <div class="field">
                      <label>左眼视力:</label>
                      <span>{{ PatientFile.leftVision || '未检查' }}</span>
                    </div>
                    <div class="field">
                      <label>右眼视力:</label>
                      <span>{{ PatientFile.rightVision || '未检查' }}</span>
                    </div>
                  </div>

                  <!-- 系统信息列 -->
                  <div class="column">
                    <div class="field">
                      <label>创建时间:</label>
                      <span>{{ formatDate(PatientFiles.createTime, "YYYY年MM月DD日 HH:mm") }}</span>
                    </div>
                    <div class="field">
                      <label>更新时间:</label>
                      <span>{{ formatDate(PatientFiles.updateTime, "YYYY年MM月DD日 HH:mm") }}</span>
                    </div>
                    <div class="field">
                      <label>紧急联系人:</label>
                      <span>{{ PatientFiles.emergencyContactName || '未填写' }}</span>
                    </div>
                    <div class="field">
                      <label>联系人电话:</label>
                      <span>{{ PatientFiles.emergencyContactPhone || '未填写' }}</span>
                    </div>
                    <div class="field">
                      <label>最后登录时间:</label>
                      <span>{{ PatientFiles.lastLoginIp || '无记录' }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </span>
          </el-tab-pane>
          <el-tab-pane label="历史病历">

            <div v-if="!HistoricalCases">暂无历史病历</div>
            <el-table :data="HistoricalCases" style="width: 100%" :row-class-name="getRowClassName">
              <el-table-column prop="patientName" label="患者姓名" width="120"></el-table-column>
              <el-table-column prop="chId" label="流水编号" width="120"></el-table-column>
              <el-table-column prop="caseDate" label="发病日期" width="120"></el-table-column>
              <el-table-column prop="careDate" label="就诊时间" width="120">
                <template #default="scope">
                  {{ formatDate(scope.row.careDate, "YYYY-MM-DD HH:mm") }}
                </template>
              </el-table-column>
              <el-table-column prop="doctorTips" label="医生建议" width="120"></el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>


      </div>

    </div>

    <!-- 右侧病历区域 -->
    <div class="right-section">
      <div class="header-info">
        <span>挂号单ID: {{ PatientFiles.regId }}</span>
        <span>病例编号:{{hisCareHistory.chId}} 保存病例后生成</span>
      </div>
      <el-tabs>
        <el-tab-pane label="病历">
          <div class="form-item">
            <label>发病日期</label>
            <el-date-picker type="date" placeholder="请选择发病日期" v-model="activeSubTab" />
          </div>
          <div class="form-item">
            <label>接诊类型</label>
            <el-select v-model="vl" placeholder="请选择接诊类型">

              <el-option v-for="item in HistoricalCase" :key="item.dict_value" :label="item.dict_label"
                :value="item.dict_value" />
            </el-select>
          </div>
          <div class="form-item">
            <label>是否传染</label>
            <el-select v-model="vl2" placeholder="请选择是否传染">
              <el-option v-for="item in TypeOfVisit" :key="item.dict_value" :label="item.dict_label"
                :value="item.dict_value" />
            </el-select>
          </div>
          <div class="form-item">
            <label>主诉</label>
            <el-input placeholder="请输入主诉" :maxlength="200" show-word-limit v-model="infect" />
          </div>
          <div class="form-item">
            <label>诊断信息</label>
            <el-input placeholder="请输入诊断信息" :maxlength="200" show-word-limit v-model="DiagnosticInformation" />
          </div>
          <div class="form-item">
            <label>医生建议</label>
            <el-input placeholder="请输入医生建议" :maxlength="200" show-word-limit v-model="DoctorAdvises" />
          </div>
          <div class="form-item">
            <label>备注</label>
            <el-input placeholder="请输入备注" :maxlength="200" show-word-limit v-model="Note" />
          </div>
          <div class="action-buttons">
            <el-button type="primary" @click="addHisCareHistory">√ 保存病历</el-button>
            <el-button type="danger" @click="addHisCareHistory2">× 就诊完成</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="处方" v-if="hisCareHistory.chId">处方内容

          <el-button type="success" @click="dialogVisible2 = true" :icon="Plus">添加药用处方</el-button>
          <el-button type="success" @click="dialogVisible = true" :icon="Plus">添加检查处方</el-button>
        </el-tab-pane>
        <!-- 添加检查处方模态框 -->
        <el-dialog title="添加【检查】处方" v-model="dialogVisible" width="600px">
          <el-button type="success" icon="el-icon-plus" @click="addItem">+ 确定添加</el-button>
          <div style="text-align: right; margin-bottom: 10px;">
            检查处方全额：￥
          </div>
          <el-table :data="tableData" style="width: 100%">
  <el-table-column prop="checkItemName" label="项目名称" />
  <el-table-column prop="unit" label="单位" />
  <el-table-column prop="unitPrice" label="单价（元）" />
  <el-table-column label="金额（元）">
    <template #default="scope">
      {{ (1* scope.row.unitPrice).toFixed(2) }}
    </template>
  </el-table-column>
  <el-table-column label="检查备注">
    <template #default="scope">
      <el-input
        v-model="scope.row.remark"
        placeholder="输入备注"
      />
    </template> 

  </el-table-column>
  <el-table-column label="删除">
    <template #default="scope">
    <el-button type="primary" @click="removetableData(scope.$index,scope.row)">删除</el-button>
  </template> 
  </el-table-column>
</el-table>
          <div v-if="tableData.length === 0" style="text-align: center; padding: 20px 0;">
            暂无数据
          </div>
          <el-button type="primary" block @click="openDrawer">添加检查项</el-button>
        </el-dialog>
      </el-tabs>

    </div>
  </div>
    <!-- 添加药品处方模态框 -->
    <el-dialog title="添加【药用】处方" v-model="dialogVisible2" width="800px">
          <el-button type="success" icon="el-icon-plus" @click="addItem2">+ 确定添加</el-button>
          <div style="text-align: right; margin-bottom: 10px;">
            检查处方全额：￥
          </div>
          <el-table :data="tableData2" style="width: 100%">
  <el-table-column prop="medicinesName" label="项目名称" />
  <el-table-column label="数量" width="240px">
      <template #default="{ row }">
        <!-- 直接使用内联定义的数量控件 -->
        <div class="inline-quantity-control">
          <el-button 
            :disabled="row.quantity <= min" 
            @click="adjustQuantity(row, -1)"
            size="small"
          >
            -
          </el-button>
          
          <el-input-number
         v-model="row.quantity"
            :min="min"
            :max="max"
            controls-position="right"
            size="small"
            @change="val => handleQuantityChange(row, val)"
            class="mx-2"
          />
          
          <el-button 
            :disabled="row.quantity >= max" 
            @click="adjustQuantity(row, 1)"
            size="small"
          >
            +
          </el-button>
        </div>
      </template>
    </el-table-column>
  <el-table-column prop="prescriptionPrice" label="单价（元）" />
  <el-table-column label="金额（元）">
    <template #default="scope">
        <!-- 添加类型检查和处理空值 -->
        {{ calculateAmount(scope) }}
    </template>
  </el-table-column>
  <el-table-column label="服用备注">
    <template #default="scope">
      <el-input
        v-model="scope.row.remark"
        placeholder="输入备注"
      />
    </template> 

  </el-table-column>
  <el-table-column label="删除">
    <template #default="scope">
    <el-button type="primary" @click="removetableData(scope.$index,scope.row)">删除</el-button>
  </template> 
  </el-table-column>
</el-table>
          <div v-if="tableData2.length === 0" style="text-align: center; padding: 20px 0;">
            暂无数据
          </div>
          <el-button type="primary" block @click="openDrawer2">添加药品项</el-button>
        </el-dialog>
  <!-- 查询患者的模态框 -->
  <el-dialog v-model="isVisible" title="选择挂号患者" width="600px" :before-close="handleClose">
    <el-tabs v-model="activeTab2">
      <el-tab-pane label="待就诊列表" name="waiting">
        <el-table :data="waitingPatients" style="width: 100%" allow-drag-last-column @row-click="handleRowClick"
          :row-class-name="getRowClassName">
          <el-table-column prop="patientName" label="患者姓名" width="120"></el-table-column>
          <el-table-column prop="regNumber" label="流水编号" width="120"></el-table-column>
          <el-table-column prop="dictLabel" label="挂号类型" width="120"></el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button type="success" size="small" @click="handleAccept(scope.row)">接诊</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 显示选中行信息 -->
        <div v-if="selectedRow">
          <h3>选中行信息</h3>
          <p>患者姓名 : {{ selectedRow.patientName }}</p>
          <p>流水编号: {{ selectedRow.regNumber }}</p>
          <p>挂号类型: {{ selectedRow.dictLabel }}</p>
        </div>
      </el-tab-pane>
      <el-tab-pane label="就诊中列表" name="consulting">
        <el-table :data="waitingPatients" style="width: 100%" @row-click="handleRowClick"
          :row-class-name="getRowClassName">
          <el-table-column prop="patientName" label="患者姓名" width="120"></el-table-column>
          <el-table-column prop="regNumber" label="流水编号" width="120"></el-table-column>
          <el-table-column prop="dictLabel" label="挂号类型" width="120"></el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button type="success" size="small" @click="handleAccept(scope.row)">接诊</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 显示选中行信息 -->
        <div v-if="selectedRow">
          <h3>选中行信息</h3>
          <p>患者姓名 : {{ selectedRow.patientName }}</p>
          <p>流水编号: {{ selectedRow.regNumber }}</p>
          <p>挂号类型: {{ selectedRow.dictLabel }}</p>
        </div>
      </el-tab-pane>
      <el-tab-pane label="就诊完成列表" name="finished">
        <el-table :data="waitingPatients" style="width: 100%" 
          :row-class-name="getRowClassName">
          <el-table-column prop="patientName" label="患者姓名" width="100%"></el-table-column>
          <el-table-column prop="regNumber" label="流水编号" width="300"></el-table-column>
          <el-table-column prop="dictLabel" label="挂号类型" width="120"></el-table-column>
        </el-table>
        <!-- 显示选中行信息 -->
        <div v-if="selectedRow">
          <h3>选中行信息</h3>
          <p>患者姓名 : {{ selectedRow.patientName }}</p>
          <p>流水编号: {{ selectedRow.regNumber }}</p>
          <p>挂号类型: {{ selectedRow.dictLabel }}</p>
        </div>

      </el-tab-pane>
    </el-tabs>
  </el-dialog>
  <!-- 添加检查抽屉 -->
  <el-drawer v-model="drawerVisible" title="检查项目列表" :direction="drawerDirection" :size="drawerSize"
    :before-close="handleBeforeClose">
    <div class="search-bar">
      <span>关键字</span>
      <el-input v-model="searchKeyword" placeholder="请输入关键字" />
      <el-button type="primary" @click="searchItems">Q 搜索</el-button>
      <el-button @click="searchKeyword = ''">🔄 重置</el-button>
    </div>
    <el-table ref="multipleTableRef" :data="Checkes" style="width: 100%" @select="handleSelectionChange"
      @select-all="handleSelectAll" @row-click="handleRowClick">
      <el-table-column type="selection" width="50"></el-table-column>
      <el-table-column prop="checkItemId" label="项目费用ID"></el-table-column>
      <el-table-column prop="checkItemName" label="项目名称"></el-table-column>
      <el-table-column prop="keywords" label="关键字"></el-table-column>
      <el-table-column prop="unitPrice" label="项目单价"></el-table-column>
      <el-table-column prop="unit" label="单位"></el-table-column>
    </el-table>
    <el-button type="primary" block @click="addAndClose">√ 添加并关闭</el-button>
  </el-drawer>
   <!-- 药品添加检查抽屉 -->
   <el-drawer v-model="drawerVisible2" title="检查项目列表" :direction="drawerDirection" :size="drawerSize"
    :before-close="handleBeforeClose">
    <div class="search-bar">
      <span>关键字</span>
      <el-input v-model="searchKeyword" placeholder="请输入关键字" />
      <el-button type="primary" @click="searchItems2">Q 搜索</el-button>
      <el-button @click="searchKeyword = ''">🔄 重置</el-button>
    </div>
    <el-table ref="multipleTableRef2" :data="Checkes2" style="width: 100%" @select="handleSelectionChange"
      @select-all="handleSelectAll" @row-click="handleRowClick">
      <el-table-column type="selection" width="50"></el-table-column>
      <el-table-column prop="medicinesNumber" label="项目费用ID"></el-table-column>
      <el-table-column prop="medicinesName" label="药品名称"></el-table-column>
      <el-table-column prop="keywords" label="关键字"></el-table-column>
      <el-table-column prop="prescriptionPrice" label="项目单价"></el-table-column>
      <el-table-column prop="unit" label="单位"></el-table-column>
    </el-table>
    <el-button type="primary" block @click="addAndClose2">√ 添加并关闭</el-button>
  </el-drawer>
</template>

<script setup lang="ts">
import { formatDate } from '@/utils/dateFormatter';//引入全局日期格式化工具
import { onMounted, ref, watch,computed } from 'vue';
import { Plus, User } from '@element-plus/icons-vue';
import 'element-plus/dist/index.css';
import { ElDialog, ElTabs, ElTabPane, ElTable, ElTableColumn, ElButton } from 'element-plus';
import http from '@/http';
import type { ComponentSize, TableInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { fa } from 'element-plus/es/locale';
import useUniqueId from '../utils/useUniqueId';//生成病例唯一编号

// 计算金额的方法
const calculateAmount = (scope) => {
  const quantity = Number(scope.row.quantity);
  const price = Number(scope.row.prescriptionPrice);
  if (isNaN(quantity) || isNaN(price) || quantity === null || price === null) {
    return 0;
  }
  return quantity * price;
};

const { uniqueId, generateUniqueId } = useUniqueId();
const multipleTableRef = ref<TableInstance>()
  const multipleTableRef2 = ref<TableInstance>()
const multipleSelection = ref<number[]>([]) // 存储选中的 deptId
const sysCheckItemIds = ref<number[]>([]) // 存储选中的 deptId
//确定添加
function addItem2(){
   // 1. 转换明细数据（移除 coId 和 createTime）
 const requestData = tableData2.value.map(item => ({
        itemRefId: item.medicinesNumber,
        itemName: item.medicinesName,
        itemType: 0,
        num: item.quantity,
        price: Number(item.prescriptionPrice),
        amount: Number(item.prescriptionPrice) *  Number(item.quantity),
        remark: item.remark,
        status: 0, // 确保 status 已定义
    }));
    console.log(requestData)
 // 2. 动态计算总金额（响应式）
 const totalAmount = computed(() => {
    return requestData.reduce((sum, item) => sum + Number(item.amount || 0), 0);
  });

  // 3. 构建处方主表数据（hisCareOrder）
  const hisCareOrder = ref({
    coType: 1,
    userId: PatientFiles.value.userId,
    patientId: PatientFiles.value.patientId,
    patientName: PatientFiles.value.patientName,
    chId: hisCareHistory.value.chId,
    allAmount:(totalAmount.value), // 动态绑定计算属性
  });

  // 4. 合并请求数据
  const requestBody = {
    careOrder: hisCareOrder.value,
    careOrderItems: requestData
  };
   // 5. 发送请求（携带 Token）
 http.post('/HisCareOrder/addcareorderitem',requestBody).then(res => {
    console.log('请求成功:', res);
  }).catch(err => {
    console.error('请求失败:', err);
  });
}


// 控制参数
const min = ref(1)
const max = ref(100)

// 数量调整方法
const adjustQuantity = (row, delta) => {
  const newValue = Number(row.quantity) + delta
  row.quantity = Math.max(min.value, Math.min(max.value, newValue))
}

// 变化处理
const handleQuantityChange = (row, newValue) => {
  console.log('数量变更:', row.id, newValue)
  // 这里可以添加数据保存逻辑
}

//控制药用处方模态框
let dialogVisible2=ref(false)
//全选
const handleSelectionChange = (selection: any[]) => {
  // 直接基于最新 selection 生成 ID 数组
  sysCheckItemIds.value = selection.map(item => item.checkItemId)

  // 若需要保留其他逻辑
  console.log('所有选中行:', selection)
  multipleSelection.value = selection
}
// 处理全选/全不选
const handleSelectAll = (selection: any[]) => {
  if (selection.length > 0) {
    // 全选时使用实际的选中数据
    multipleSelection.value = selection
    // 使用 Set 自动去重
    const newIds = new Set([
      ...sysCheckItemIds.value,
      ...selection.map(item => item.checkItemId)
    ])
    sysCheckItemIds.value = Array.from(newIds)
  } else {
    // 全不选时删除当前页所有ID
    const currentPageIds = Checkes.value.map(item => item.checkItemId)
    sysCheckItemIds.value = sysCheckItemIds.value.filter(
      id => !currentPageIds.includes(id)
    )
    multipleSelection.value = []
  }
  console.log('当前选中ID:', sysCheckItemIds.value)
}

// 处理行点击
const handleRowClick2 = (row: any, column: any, event: Event) => {
  // 排除点击的是复选框的情况
  if (column.type !== 'selection') {
    multipleTableRef.value?.toggleRowSelection(row)
    console.log('点击行数据:', row)
  }
}

// 获取选中数据
const getSelectedRows = () => {
  return multipleTableRef.value?.getSelectionRows() || []
}

// 全选
const selectAll = () => {
  Checkes.value.forEach((row) => {
    multipleTableRef.value?.toggleRowSelection(row, true)
  })
}

// 全不选
const clearSelection = () => {
  multipleTableRef.value?.clearSelection()
}

//控制患者档案
let activeTab = ref(false)
// 控制对话框显示隐藏
const isVisible = ref(false);
// 当前激活的标签页
const activeTab2 = ref('waiting');

// 不同状态的患者数据
const waitingPatients = ref([]);

// 不同状态的分页信息
const waitingPageNum = ref(1);
const waitingPageSize = ref(10);
const waitingTotal = ref(0);



// 关闭对话框的处理函数
const handleClose = (done) => {
  done();
};

// 接诊操作的处理函数
const handleAccept = (patient) => {
  patientNew.value = patient

  selectedRow.value = patient; // 更新选中的行数据
  console.log(patientNew.value)
  console.log('接诊患者:', patient);
  //隐藏模态框
  isVisible.value = false;
};
let pageNum = ref('1')
let pageSize = ref('10')
// 获取患者数据
const getpatient = async (status) => {
  console.log(activeTab2.value)
  isVisible.value = true
  //发送http请求
  http.get("/registration/getHisRegistrationregStatus?regStatus=" + status + "&pageNum=" + pageNum.value + "&pageSize=" + pageSize.value).then((res) => {
    waitingPatients.value = res

  }).catch((res) => {
  })

};

// 待就诊列表分页处理
const handleWaitingSizeChange = (val: number, newSize) => {
  waitingPageSize.value = val;
  getpatient(newSize);
};
const handleWaitingCurrentChange = (val: number, newPage) => {
  waitingPageNum.value = val;
  getpatient(newPage);
};
// 监听activeTab2属性的变化
watch(activeTab2, (newValue, oldValue) => {
  selectedRow.value = null;
  console.log(`activeTab2的值从 ${oldValue} 变为了 ${newValue}`);
  // 在这里可以执行其他逻辑，比如根据新值进行不同的操作
  if (newValue == "waiting") {
    getpatient('1')
  }
  if (newValue == "consulting") {
    getpatient('2')

  }
  if (newValue == "finished") {
    getpatient('3')
  }
});
//存储患者信息
let patientNew = ref({
  address: "",
  allergyInfo: null,
  birthday: "",
  createBy: "",
  createTime: "",
  phone: '',
  deptId: null,
  dictLabel: "",
  doctorName: "",
  hisPatientFile: null,
  idCard: "",
  patientId: "",
  patientName: "",
  regId: "",
  regItemAmount: null,
  regItemId: null,
  regNumber: null,
  regStatus: "",
  schedulingType: "",
  sex: "",
  subsectionType: "",
  updateTime: "",
  userId: "",
  visitDate: "",
})
//存储患者档案信息
let PatientFiles = ref({})
let PatientFile = ref({})
//存储患者历史病例
let HistoricalCases = ref();
const selectedRow = ref(null); // 存储选中的行数据
//查询部门
let dept = ref('')
const handleRowClick = (row) => {
  console.log(row)
  PatientFile.value = row.hisPatientFile
  PatientFiles.value = row
  console.log(row.hisPatientFile)
  console.log("患者档案信息" + PatientFiles.value)
  patientNew.value = row
  selectedRow.value = row; // 更新选中的行数据
  activeTab.value = true;
  console.log("患者信息" + JSON.stringify(row, null, 2))

  //发送http请求查询部门名称
  http.get("/hiscarehistory/getDept?patient=" + PatientFiles.value.patientId).then((res) => {
    dept.value = res
  }).catch((res) => {
    console.log("失败")
  })
  //发送http请求根据患者id查询患者的病例历史
  http.get("/hiscarehistory/gethiscarehistoryById?patient=" + PatientFiles.value.patientId).then((res) => {
    HistoricalCases.value = res
    console.log("A")
  }).catch((res) => {

  }).finally(() => {

  })
};
const getRowClassName = ({ row }) => {
  if (selectedRow.value && row.regId === selectedRow.value.regId) {
    return 'selected-row'; // 为选中的行添加样式
  }
  return '';
};
let patientNewAge = ref('')
//修改患者属性
function setAge() {
  const birthDate = new Date(patientNew.value.birthday);
  const currentDate = new Date();
  let age = currentDate.getFullYear() - birthDate.getFullYear();
  const monthDiff = currentDate.getMonth() - birthDate.getMonth();
  if (monthDiff < 0 || (monthDiff === 0 && currentDate.getDate() < birthDate.getDate())) {
    age--;
  }
  patientNewAge.value = age.toString();
}
//监听患者出生日期
watch(() => patientNew.value.birthday, (newValue, oldValue) => {
  if (newValue !== oldValue) {
    setAge();
  }
})
let vl2 = ref('')
//接诊类型
let HistoricalCase = ref([])
const fetchDictData = async (dictType) => {
  await http.get('/api/dict/data/' + dictType).then((res) => {
    HistoricalCase.value = res;
  }).catch((error) => {
    console.error('获取字典数据失败:', error);
  })
};
let vl = ref('');
//是否传染
let TypeOfVisit = ref([])
const fetchDictData2 = async (dictType) => {
  await http.get('/api/dict/data/' + dictType).then((res) => {
    TypeOfVisit.value = res;
  }).catch((error) => {
    console.error('获取字典数据失败:', error);
  })
};
//窗体加载完成之后
onMounted(() => {
  fetchDictData("his_receive_type")
  fetchDictData2("his_contagious_status")
})

//发病日期
let activeSubTab = ref('')
//主诉
let infect = ref('')
//诊断信息
let DiagnosticInformation = ref('')
//医生建议
let DoctorAdvises = ref('')
//备注
let Note = ref('')
// 定义一个病例表对象
let hisCareHistory = ref({
  chId: "",
  userId: null,
  userName: "",
  patientId: "",
  patientName: "",
  deptId: null,
  deptName: "",
  receiveType: "",
  isContagious: "",
  careDate: "",
  caseDate: "",
  regId: "1",
  caseTitle: "",
  caseResult: "",
  doctorTips: "",
  remark: ""
});
const tableData2 = ref([]) // 表格数据源
//患者id
let patientId=ref('')
import {  ElMessageBox } from 'element-plus'
// 保存病例按钮
function addHisCareHistory() {
 
  //弹出确认提示信息
  ElMessageBox.confirm(
    '确定要保存病例吗?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      ElMessage({
        type: 'success',
        message: '正在执行操作',
      })

//  //判断是否选中患者
//  if (!selectedRow.value || 
//     hisCareHistory.value.doctorTips === "" || 
//     DiagnosticInformation.value === "" || 
//     DoctorAdvises.value === "" || 
//     infect.value === "" || 
//     vl2.value === "" || 
//     vl.value === "") {
//     // 弹出消息提示框
//     ElMessage({
//       message: '还未选择患者或信息值为空',
//       type: 'warning',
//     });
//     alert("ACCA")
//     return;
//   }

    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })

  hisCareHistory.value.chId =generateUniqueId();//病例编号
  hisCareHistory.value.userId = PatientFiles.value.userId;//医生id
  hisCareHistory.value.userName = PatientFiles.value.doctorName;//医生名称
  hisCareHistory.value.patientId = PatientFiles.value.patientId//患者id
  hisCareHistory.value.patientName = PatientFiles.value.patientName//患者姓名
  hisCareHistory.value.deptId = PatientFiles.value.deptId;//科室id
  hisCareHistory.value.deptName = dept.value;//科室名称
  hisCareHistory.value.receiveType = vl2.value;//接诊类型：0初诊，1复诊
  hisCareHistory.value.isContagious = vl.value;//是否传染
  hisCareHistory.value.careDate = formatDate(PatientFiles.value.visitDate, "YYYY-MM-DD");//就诊时间
  hisCareHistory.value.regId = PatientFiles.value.regId;//挂号id
  // 给病例表赋值 {{ formatDate(scope.row.careDate, "YYYY-MM-DD HH:mm") }}
  hisCareHistory.value.caseDate = formatDate(activeSubTab.value, "YYYY-MM-DD");
  hisCareHistory.value.caseTitle = infect.value;
  hisCareHistory.value.caseResult = DiagnosticInformation.value;
  hisCareHistory.value.doctorTips = DoctorAdvises.value;
  hisCareHistory.value.remark = Note.value;

  // 发送 http 请求
  http.post("/hiscarehistory/addHiscarehistory", hisCareHistory.value).then((res) => {
    console.log("成功", res);
  }).catch(() => {
    console.log("失败");
  })
    selectedRow.value = null;
}
// 保存病例按钮
function addHisCareHistory2() {
 
 //弹出确认提示信息
 ElMessageBox.confirm(
   '确定要完成就诊吗?',
   'Warning',
   {
     confirmButtonText: '确定',
     cancelButtonText: '取消',
     type: 'warning',
   }
 )
   .then(() => {
  
//判断是否选中患者
// if ( !selectedRow.value || 
//     hisCareHistory.value.doctorTips === "" || 
//     DiagnosticInformation.value === "" || 
//     DoctorAdvises.value === "" || 
//     infect.value === "" || 
//     vl2.value === "" || 
//     vl.value === "") {
//       alert("A")
//    // 弹出消息提示框
//    console.log("selectedRow",selectedRow.value)
//    ElMessage({
//      message: '还未选择患者或信息值为空',
//      type: 'warning',
//    });
//    return;
//  }
    ElMessage({
       type: 'success',
       message: '正在执行操作',
     })

   })
   .catch(() => {
     ElMessage({
       type: 'info',
       message: '取消操作',
     })
   })
alert("执行操作")
 hisCareHistory.value.chId =generateUniqueId();//病例编号
 hisCareHistory.value.userId = PatientFiles.value.userId;//医生id
 hisCareHistory.value.userName = PatientFiles.value.doctorName;//医生名称
 hisCareHistory.value.patientId = PatientFiles.value.patientId//患者id
 hisCareHistory.value.patientName = PatientFiles.value.patientName//患者姓名
 hisCareHistory.value.deptId = PatientFiles.value.deptId;//科室id
 hisCareHistory.value.deptName = dept.value;//科室名称
 hisCareHistory.value.receiveType = vl2.value;//接诊类型：0初诊，1复诊
 hisCareHistory.value.isContagious = vl.value;//是否传染
 hisCareHistory.value.careDate = formatDate(PatientFiles.value.visitDate, "YYYY-MM-DD");//就诊时间
 hisCareHistory.value.regId = PatientFiles.value.regId;//挂号id
 // 给病例表赋值 {{ formatDate(scope.row.careDate, "YYYY-MM-DD HH:mm") }}
 hisCareHistory.value.caseDate = formatDate(activeSubTab.value, "YYYY-MM-DD");
 hisCareHistory.value.caseTitle = infect.value;
 hisCareHistory.value.caseResult = DiagnosticInformation.value;
 hisCareHistory.value.doctorTips = DoctorAdvises.value;
 hisCareHistory.value.remark = Note.value;

 // 发送 http 请求
 http.post("/hiscarehistory/addHiscarehistory2", hisCareHistory.value).then((res) => {
   console.log("成功", res);
 }).catch(() => {
   console.log("失败");
 })
   selectedRow.value = null;
}
// 控制对话框显示隐藏
const dialogVisible = ref(false);
// 表格数据
const tableData = ref([]);

// 模拟添加确定添加的逻辑（目前只是简单的 console 输出）
  const addItem = () => {
  // 1. 转换数据结构（检查项目明细表）
 // 1. 转换明细数据（移除 coId 和 createTime）
 const requestData = tableData.value.map(item => ({
        itemRefId: item.checkItemId,
        itemName: item.checkItemName,
        itemType: 1,
        num: 1.0,
        price: Number(item.unitPrice),
        amount: Number(item.unitPrice) * 1.0,
        remark: item.remark,
        status: 0, // 确保 status 已定义
    }));

  // 2. 动态计算总金额（响应式）
  const totalAmount = computed(() => {
    return requestData.reduce((sum, item) => sum + Number(item.amount || 0), 0);
  });

  // 3. 构建处方主表数据（hisCareOrder）
  const hisCareOrder = ref({
    coType: 1,
    userId: PatientFiles.value.userId,
    patientId: PatientFiles.value.patientId,
    patientName: PatientFiles.value.patientName,
    chId: hisCareHistory.value.chId,
    allAmount:(totalAmount.value), // 动态绑定计算属性
  });

  // 4. 合并请求数据
  const requestBody = {
    careOrder: hisCareOrder.value,
    careOrderItems: requestData
  };
  console.log('执行确定添加操作');
  //发送http请求往检查和用药项目明细表添加数据
 // 5. 发送请求（携带 Token）
 http.post('/HisCareOrder/addcareorderitem',requestBody).then(res => {
    console.log('请求成功:', res);
  }).catch(err => {
    console.error('请求失败:', err);
  });
};



// 模拟添加检查项的逻辑（目前只是简单的向表格添加一条空数据）
const addCheckItem = () => {
  tableData.value.push({
    itemName: '',
    unit: '',
    unitPrice: '',
    amount: '',
    remark: ''
  });
};


const checkItemDrawerRef = ref(null);
//存储所有检查项
let Checkes = ref([])
let Checkes2 = ref([])
const openDrawer = () => {
  //发送http请求,查询检查费用表weweqwerrrrrrrrrrrrrrr
  http.get("/sysCheckItem/getAll?keywords=" + searchKeyword.value).then((res) => {
    Checkes.value = res
    console.log("成功" + res)
  }).catch(() => {

    console.log("失败")
  })
  drawerVisible.value = true;
};
//药品
const openDrawer2 = () => {
  //发送http请求,查询检查费用表weweqwerrrrrrrrrrrrrrr
  http.get("/StockMedicines/getAll?keywords=" + searchKeyword.value).then((res) => {
    Checkes2.value = res
    console.log("成功" + res)
  }).catch(() => {

    console.log("失败")
  })
  drawerVisible2.value = true;
};
//
// 控制抽屉显示隐藏
const drawerVisible = ref(false);
// 控制抽屉显示隐藏
const drawerVisible2 = ref(false);
// 抽屉方向（这里是右侧滑出）
const drawerDirection = ref('rtl');
// 抽屉大小
const drawerSize = ref('50%');


// 搜索关键字
const searchKeyword = ref('');

// 搜索方法
const searchItems = () => {
  //调用查询所有检查项目费用表
  openDrawer();

  // 这里可以实现实际的搜索逻辑，目前简单返回全部数据
  console.log('执行搜索操作，关键字：', searchKeyword.value);
};
// 搜索方法
const searchItems2 = () => {
  //调用查询所有检查项目费用表
  openDrawer2();
  
  // 这里可以实现实际的搜索逻辑，目前简单返回全部数据
  console.log('执行搜索操作，关键字：', searchKeyword.value);
};
// 重置搜索方法
const resetSearch = () => {
  searchKeyword.value = '';
  console.log('执行重置操作');
};

// 关闭抽屉前的回调
const handleBeforeClose = (done) => {
  done();
};
// 正确定义接口
interface CareOrderItem {
  itemId: string;
  coId: string;
  itemRefId: string;
  itemName: string;
  itemType: '0' | '1';  // 限定只能为'0'或'1'
  num: number;
  price: number;
  amount: number;
  remark: string;
  status: '0' | '1' | '2' | '3'; // 限定状态值范围
  createTime: string;             // ISO时间字符串格式
}
// 响应式对象
const careOrderItem = ref<CareOrderItem>({
  itemId: '',
  coId: '',
  itemRefId: '',
  itemName: '',
  itemType: '0',
  num: 0,
  price: 0,
  amount: 0,
  remark: '',
  status: '0',
  createTime: formatDate( new Date().toISOString(),"yyyy-mm-dd  HH:SS")
});

// 根据业务需求选择合适的唯一字段：
const uniqueKey = 'itemRefId'; // 推荐使用业务唯一标识（如药品ID、检查项目ID）
// 或使用复合键：
const getUniqueKey = item => `${item.type}-${item.code}`;
// 添加并关闭抽屉方法
const addAndClose = () => {
  // 使用对象存储已有数据（O(1)查找复杂度）
  const existingMap = tableData.value.reduce((acc, item) => {
    acc[item.itemRefId] = true;
    return acc;
  }, {});

  tableData.value = [
    ...tableData.value,
    ...multipleSelection.value
      .filter(item => !existingMap[item.itemRefId])
      .map(item => ({ 
        ...item,
        itemId: crypto.randomUUID()
      }))
  ];
  console.log(tableData.value)
}
// 添加并关闭抽屉方法
const addAndClose2 = () => {
  // 使用对象存储已有数据（O(1)查找复杂度）
  const existingMap = tableData2.value.reduce((acc, item) => {
    acc[item.itemRefId] = true;
    return acc;
  }, {});

  tableData2.value = [
    ...tableData2.value,
    ...multipleSelection.value
      .filter(item => !existingMap[item.medicinesId])
      .map(item => ({ 
        ...item,
        itemId: crypto.randomUUID(),
        quantity:1,
        prescriptionPrice:Number(item.prescriptionPrice) ||0
      }))
  ];
}
// 添加响应式监控
watch(
  () => tableData2.value,
  (newVal) => {
    console.log('数据变更:', newVal)
  },
  { deep: true }
)
//添加检查处方的删除按钮
function removetableData(index: number, row) {
  console.log(index)
  multipleSelection.value.splice(index, 1)
  //multipleSelection.value.removeChild('需要删除的节点')
  console.log("当前行", row)
}
//控制数量的控件

</script>

<style scoped>
/* 数量控件 */
.inline-quantity-control {
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-input-number__decrease),
:deep(.el-input-number__increase) {
  display: none;
}
.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.search-bar span {
  margin-right: 10px;
}

.selected-row {
  background-color: #f0f7ff;
  /* 选中行的背景色 */
  font-weight: bold;
  /* 选中行的字体加粗 */
}

.medical-record-container {
  display: flex;
  gap: 20px;
}

.left-section {
  width: 30%;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 20px;
}

.right-section {
  width: 70%;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 20px;
}

.form-item {
  margin-bottom: 15px;
}

.form-item label {
  display: block;
  margin-bottom: 5px;
}

.icon {
  position: absolute;
  right: 10px;
  top: 10px;
  cursor: pointer;
}

.patient-archive {
  margin-top: 20px;
}

.header-info {
  margin-bottom: 15px;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>